package com.it.admin.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.admin.AdminTypeService;
import com.it.dao.TypeMapper;
import com.it.dao.TypeMapper;
import com.it.pojo.Type;
import com.it.pojo.Type;
import com.it.pojo.params.BasePage;
import com.it.pojo.vo.type.AdminTypeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class AdminTypeServiceImpl implements AdminTypeService {
    @Resource
    private TypeMapper typeMapper;


    @Override
    public List<AdminTypeVO> listCategories() {
        List<Type> types = typeMapper.selectList(null);
        List<AdminTypeVO> adminTypeVOS = copyList(types);
        return adminTypeVOS;
    }

    @Override
    public int insertType(String typeName) {
        Type type = new Type();
        Date date = new Date();
        type.setGmtCreate(date);
        type.setGmtModified(date);
        type.setTypeName(typeName);

        return typeMapper.insert(type);
    }

    @Override
    public Map<String, Object> listCategories(BasePage basePage) {
        Page<Type> page = new Page<>(basePage.getPageNum(), basePage.getLimit());
        Page<Type> typePage = typeMapper.selectPage(page, null);
        Map<String, Object> map = new HashMap<>();
        map.put("total", typePage.getTotal());
        map.put("listType", typePage.getRecords());
        return map;
    }

    @Override
    public int deleteTypeById(Integer typeId) {

        return typeMapper.deleteById(typeId);
    }

    @Override
    public int updateTypeById(Type type) {
        System.out.println("type = " + type);
        type.setGmtModified(new Date());
        return typeMapper.updateById(type);
    }

    @Override
    public String getType(Integer typeId) {
        Type type = typeMapper.selectById(typeId);
        if (type != null) {
            return type.getTypeName();
        }
        return "";
    }

    private AdminTypeVO copy(Type type) {
        AdminTypeVO adminTypeVO = new AdminTypeVO();
        BeanUtils.copyProperties(type, adminTypeVO);
        return adminTypeVO;
    }

    private List<AdminTypeVO> copyList(List<Type> typeList) {
        List<AdminTypeVO> list = new ArrayList<>();
        for (Type type : typeList) {
            list.add(copy(type));
        }
        return list;
    }
}
